package xzit.gcxy.xxhzx.zhh.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.hibernate.criterion.DetachedCriteria;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import xzit.gcxy.xxhzx.zhh.client.Client;
import xzit.gcxy.xxhzx.zhh.common.AjaxJson;
import xzit.gcxy.xxhzx.zhh.common.Pagination;
import xzit.gcxy.xxhzx.zhh.common.ResourceUtil;
import xzit.gcxy.xxhzx.zhh.entity.InstituteVO;
import xzit.gcxy.xxhzx.zhh.entity.ManagedAccount4ajax;
import xzit.gcxy.xxhzx.zhh.entity.ManagedAccountVO;
import xzit.gcxy.xxhzx.zhh.service.AccountService;

@Controller
@RequestMapping("/accountManageController")
public class AccountManageController {
	private static final Logger logger = Logger.getLogger(AccountManageController.class);

	@Autowired
	private AccountService accountService;

	/**
	 * 科研工作量详情页
	 * 
	 * @param error
	 * @param model
	 * @return
	 */
	@RequestMapping(params = "goUpdate")
	public ModelAndView goSWDetail(HttpServletRequest request) {
		return new ModelAndView("system/update");
	}

	@RequestMapping(params = "updatepwd")
	@ResponseBody
	public AjaxJson updatePWD(HttpServletRequest request, HttpServletResponse response, String oldpwd, String newpwd)
			throws Exception {
		AjaxJson j = new AjaxJson();

		j.setMsg("保存成功！");
		j.setSuccess(true);
		try {
			Client client = ResourceUtil.getClient();
			ManagedAccountVO user = client.getUser();
			user.setPassword(oldpwd);
			user = accountService.getUserByNameAndPassword(user);
			if (user == null) {
				j.setSuccess(false);
				j.setMsg("用户名或密码错误！");
				return j;
			}
			Md5Hash md5Hash = new Md5Hash(newpwd);
			String password = md5Hash.toHex();
			user.setPassword(password);
			accountService.update(user);
		} catch (Exception e) {
			j.setMsg("保存失败！");
			j.setSuccess(false);
		}

		return j;

	}

	/**
	 * 初始访问
	 * 
	 * @param
	 * @param model
	 * @return
	 */
	@RequestMapping(params = "goAccount")
	public ModelAndView goScore(HttpServletRequest request) {
		return new ModelAndView("system/account");
	}

	@RequestMapping(params = "save")
	@ResponseBody
	public AjaxJson save(HttpServletRequest request, HttpServletResponse response, ManagedAccount4ajax vo)
			throws Exception {
		AjaxJson j = new AjaxJson();
		j.setMsg("保存成功！");
		j.setSuccess(true);
		DetachedCriteria condition = DetachedCriteria.forClass(InstituteVO.class);
		List<InstituteVO> insList= accountService.getQueryData(condition);
		try {
			
			ManagedAccountVO tempvo = new ManagedAccountVO();
			tempvo.setLevel(vo.getLevel());
			tempvo.setOther(vo.getOther());
			tempvo.setPassword(new Md5Hash(vo.getPassword()).toHex());
			tempvo.setUsername(vo.getUsername());
			
			for(InstituteVO invo: insList){
				if(invo.getInstitute().equals(vo.getInstitute())){
					tempvo.setInstitute(invo);
				}
			}
			if(tempvo.getInstitute() == null){
				j.setMsg("不存在该部门！");
				j.setSuccess(false);
				return j;
			}
			accountService.save(tempvo);
		} catch (Exception e) {
			j.setMsg("保存失败！");
			j.setSuccess(false);
		}
		return j;

	}

	@RequestMapping(params = "delete", method = RequestMethod.POST)
	@ResponseBody
	public AjaxJson delete(HttpServletRequest request, HttpServletResponse response, String ids) throws Exception {
		AjaxJson j = new AjaxJson();
		j.setMsg("删除成功！");
		j.setSuccess(true);
		try {
			for (String id : ids.split(",")) {
				ManagedAccountVO tempvo = accountService.get(ManagedAccountVO.class, Integer.parseInt(id));
				accountService.delete(tempvo);
			}
		} catch (Exception e) {
			j.setMsg("删除失败！");
			j.setSuccess(false);
		}
		return j;

	}

	@RequestMapping(params = "datagrid")
	@ResponseBody
	public void datagrid(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String page = request.getParameter("page");// easyui datagrid 分页 页号
		String rows = request.getParameter("rows");// easyui datagrid 分页 页数
		if (page == null) {
			page = "0";
		}
		if (rows == null) {
			rows = "0";
		}
		DetachedCriteria condition = DetachedCriteria.forClass(ManagedAccountVO.class);
		Pagination<?> pagination = accountService.findPageData(condition, Integer.parseInt(page),
				Integer.parseInt(rows));

		JSONObject jobj = new JSONObject();
		jobj.put("total", pagination.getTotalCount());
		jobj.put("rows", pagination.getDatas());

		response.setCharacterEncoding("utf-8");
		response.getWriter().write(jobj.toString());

	}
}
